layui.define(['form','jquery', 'laypage'], function (exports) {
    var $ = layui.jquery, laypage = layui.laypage,form = layui.form();
    $.fn.jfTable = function (_opt, args) {
        if (typeof _opt == "string") {//判断是方法还是对象
            return JfTable.methods[_opt](this, args);
        }
        _opt = _opt || {};
        return this.each(function () {
            var grid = $.data(this, "jfTable");
            if (grid) {
                _opt = $.extend(grid.options, _opt);
                grid.options = _opt;
            } else {
                grid=new JfTable(this,_opt);
                $(this).data('jfTable',grid);
            }
        });
    }


    var JfTable=function (element,option) {
        this.$element=$(element);

        this.defaultConfig={
            columns: [],
            url: null,
            data:[],
            method:"get",
            select:false,
            toolbar:[],
            pageSize:20,
            queryParam: {},
            onBeforeLoad: function (param) {
                return param;
            },
            onLoadSuccess: function (data) {
                return data;
            },
            dataFilter:function (res) {
                return res;
            }
        };
        //var opts = $.extend(this.defaultConfig, option);
        this.$element.data('options', $.extend(this.defaultConfig, option));
        if(option.select){
            option.columns.unshift({
                type:'check',
                width: 50
            });
        }
        this.option = $.extend(this.defaultConfig, option);
        this.init();
        if(option.page){
            this.initPage();
        }
    }

    JfTable.prototype.init=function () {
        $("<table class='layui-table'></table>").appendTo(this.$element.html(""));
        if(this.option.url){
            this.ajaxData();
        }
        this.initBody();
        this.initToolbar();
    };

    JfTable.prototype.resetPager=function () {
        var t=this,opt=t.option,page=$("div[id='" + t.$element[0].id + "_pb']");
        laypage({
            cont: page,
            curr: opt.pageNumber,
            pages:opt.pages,
            groups: 5,
            jump: function (obj,s) {
                t.option.queryParam=$.extend(opt.queryParam,{pageNumber:obj.curr});
                if(!s){
                    t.init();
                }
            }
        });
    }

    JfTable.prototype.initEvent=function () {
        var t=this,_opt=t.option;
        if(_opt.select){
            form.render("checkbox");
            form.on('checkbox(allChoose)', function(data){
                var child = $(data.elem).parents('table').find('tbody input[type="checkbox"]');
                child.each(function(index, item){
                    item.checked = data.elem.checked;
                });
                form.render('checkbox');
            });
        }
    }

    JfTable.prototype.prettyStyle=function() {
        var t=this, $e=t.$element;
        $e.css('overflow', 'auto');
        var table = $e.find('table');
        var len = 0;
        var columns = t.option.columns;
        for (var i=0; i<columns.length; i++) {
            len += columns[i].width;
        }
        table.css('width', len + 'px');
    }

    JfTable.prototype.initToolbar=function () {
        var t=this,$e=t.$element,_opt=t.option,toolbar=_opt.toolbar,tool= $("<div class='layui-btn-group'></div>").prependTo($e);
        $.each(toolbar,function (index,item) {
            var btn=$("<button class='layui-btn "+_opt.toolbarClass+"'></button>").appendTo(tool);
            if(item.icon){
                $("<i class='layui-icon'>"+item.icon+"</i>").appendTo(btn);
            }else{
                btn.append(item.text);
            }
            btn[0].onclick=eval(item.handle||function (){});
        });
    }

    JfTable.prototype.initPage=function () {
       var t=this,$e=t.$element,opt=t.option, page=$("<div class='page-bar' id='" + t.$element[0].id + "_pb'></div>").insertAfter($e);
        laypage({
            cont: page,
            curr: opt.pageNumber,
            pages:opt.pages,
            groups: 5,
            jump: function (obj,s) {
                t.option.queryParam=$.extend(opt.queryParam,{pageNumber:obj.curr});
                if(!s){
                    t.init();
                }
            }
        });
    }

    JfTable.prototype.initBody=function () {
        var t=this,$e=t.$element,opt=t.option,col=opt.columns,dt=opt.data,

            $table=$e.find("table").html(""),
            $cg=$("<colgroup></colgroup>").appendTo($table),
            $th=$("<thead></thead>").appendTo($table),
            $thr=$("<tr></tr>").appendTo($th),
            $tb=$("<tbody></tbody>").appendTo($table);
        $tb.html("");
        if(opt.select){
            $table.wrapAll("<div class='layui-form'></div>");
        }

        for(var i=0,l=col.length;i<l;i++){
            var c=col[i];
            i==(l-1)?$("<col>").appendTo($cg):$("<col width='"+c.width+"'>").appendTo($cg);
            c.type=='check'?$("<th><div class='layui-elip' style='width:" + c.width + "px'><input type='checkbox' lay-skin='primary' lay-filter='allChoose'></div></th>").appendTo($thr):$("<th><div class='layui-elip' style='width:" + c.width + "px'>"+c.text+"</div></th>").appendTo($thr);
        }

        for(var i=0,l=dt.length;i<l;i++){
            var d=dt[i],$tr=$("<tr></tr>").appendTo($tb);
            for(var j=0,cl=col.length;j<cl;j++){
                var c=col[j],f=c.formatter;
                var v = null;
                var objFields = c.name.split('.');
                for (var k=0; k<objFields.length; k++) {
                    if (k==0) {
                        v=d[objFields[k]];
                    } else {
                        if (v != null && v != undefined) {
                            v=v[objFields[k]];
                        }
                    }
                }
                if(c.type=='check'){
                    $("<td><input type='checkbox' value='"+i+"' lay-skin='primary'></td>").appendTo($tr);
                    continue;
                }
                if(typeof f == "function"){
                    v=f(v,d,i);
                }
                var align = 'center';
                if (c.align) {
                    align = c.align;
                }
                if (v==null || v==undefined) {
                    v = '';
                }
                //$("<td style='text-align:" + align + "'><div class='layui-elip' style='width:" + c.width + "px'>"+v+"</div></td>").appendTo($tr);
                $("<td style='text-align:" + align + "'><div style='width:" + c.width + "px'>"+v+"</div></td>").appendTo($tr);
            }
        }
        t.prettyStyle();
        opt.onLoadSuccess(dt);
        if(opt.select){
            t.initEvent();
        }
    }

    JfTable.prototype.ajaxData=function () {
        var opt=this.option,param=$.extend({},opt.queryParam,{pageSize:opt.pageSize}),
            result=$.ajax({
                url: opt.url,
                method:opt.method,
                data:opt.onBeforeLoad(param),
                async:false
            }).responseJSON;
        opt.dataFilter(result);
        if(opt.page){
            opt.pages=result.totalPage;
            opt.curr=result.pageNumber;
        }
        opt.data= result.list;
    }

    JfTable.methods={
        option: function (jq) {
            return $.data(jq[0], "jfTable").option;
        },
        insertRow: function (jq, row) {
            var s=$.data(jq[0],"jfTable"),opt=s.option;
            opt.data.unshift(row);
            s.initBody();
        },
        getRow: function (jq, args) {
            var s=$(jq[0]).jfTable('option');
            return s.data[args];
        },
        reload: function (jq, param) {
            var t=$.data(jq[0],"jfTable"),opt=t.option;
            opt.param=$.extend({},opt.queryParam,param);
            t.init();
            t.resetPager();
        },
        updateRow:function (jq,param) {
            var s=$.data(jq[0],"jfTable"),opt=s.option;
            opt.data[param.index]=param.row;
            s.initBody();
        },
        getSelected:function (jq) {
           var s = $(jq[0]).find("table.layui-table tbody .layui-form-checked"),r=[];
           for(var i=0,l=s.length;i<l;i++){
               r[i]=$(s[i]).prev().val();
           }
           return r || undefined;
        }

    };

    exports('jfTable', {});
});
